<template>
  <div class="user-follows-container">
    <!-- 搜索栏 -->
    <el-row class="search-row">
      <el-col :span="24" :xs="24" :sm="16" :md="16" :lg="8">
        <el-input
          v-model="searchParams.followerId" 
          placeholder="请输入关注者ID" 
          style="width: 100%;"
        ></el-input>
      </el-col>
      <el-col :span="24" :xs="24" :sm="8" :md="8" :lg="8" class="button-group">
        <el-button
          type="danger"
          size="large"
          @click="loadUserFollowsList"
          style="margin-right: 10px; margin-bottom: 10px;"
        >
          <i class="el-icon-search"></i> 搜索
        </el-button>
        <el-button
          type="primary"
          size="large"
          @click="showAddDialog"
        >
          <i class="el-icon-circle-plus"></i> 添加关注
        </el-button>
      </el-col>
    </el-row>

    <!-- 添加关注对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加关注"
      width="450px"
    >
      <el-form ref="addForm" :model="addForm" label-width="100px">
        <el-form-item label="关注者ID" :rules="{ required: true, message: '请输入关注者ID', trigger: 'blur' }">
          <el-input v-model.number="addForm.followerId" autocomplete="off" type="number"></el-input>
        </el-form-item>
        <el-form-item label="被关注者ID" :rules="{ required: true, message: '请输入被关注者ID', trigger: 'blur' }">
          <el-input v-model.number="addForm.followedId" autocomplete="off" type="number"></el-input>
        </el-form-item>
        <el-form-item label="是否互关" :rules="{ required: true, message: '请选择是否互关', trigger: 'change' }">
          <el-radio-group v-model="addForm.mutual">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addUserFollows">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑关注对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑关注"
      width="450px"
    >
      <el-form ref="editForm" :model="editForm" label-width="100px">
        <el-form-item label="记录ID">
          <el-input v-model="editForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="关注者ID" :rules="{ required: true, message: '请输入关注者ID', trigger: 'blur' }">
          <el-input v-model.number="editForm.followerId" autocomplete="off" type="number"></el-input>
        </el-form-item>
        <el-form-item label="被关注者ID" :rules="{ required: true, message: '请输入被关注者ID', trigger: 'blur' }">
          <el-input v-model.number="editForm.followedId" autocomplete="off" type="number"></el-input>
        </el-form-item>
        <el-form-item label="是否互关" :rules="{ required: true, message: '请选择是否互关', trigger: 'change' }">
          <el-radio-group v-model="editForm.mutual">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="editForm.createTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="更新时间">
          <el-input v-model="editForm.updateTime" disabled></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateUserFollows">确定</el-button>
      </template>
    </el-dialog>

    <!-- 状态容器 -->
    <div class="state-container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-mask">
        <el-loading-spinner size="large"></el-loading-spinner>
        <p>正在加载数据，请稍候...</p>
      </div>

      <!-- 空数据提示 -->
      <div v-else-if="userFollowsList.length === 0" class="empty-data">
        <i class="el-icon-data-empty"></i>
        <p>暂无关注记录数据</p>
        <el-button type="primary" @click="loadUserFollowsList">刷新</el-button>
      </div>

      <!-- 关注记录列表 -->
      <el-table
        v-else
        :data="userFollowsList"
        stripe
        highlight-current-row
        border
        fit
        style="width: 100%; margin-top: 20px;"
      >
        <el-table-column
          prop="id"
          label="记录ID"
          min-width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="followerId"
          label="关注者ID"
          min-width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="followedId"
          label="被关注者ID"
          min-width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="mutual"
          label="是否互关"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            <el-tag :type="scope.row.mutual === 1 ? 'success' : 'info'">
              {{ scope.row.mutual === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="isDesktop"
          prop="createTime"
          label="创建时间"
          min-width="160"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="isDesktop"
          prop="updateTime"
          label="更新时间"
          min-width="160"
          align="center"
        ></el-table-column>
        <el-table-column
          label="操作"
          min-width="160"
          align="center"
        >
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="showEditDialog(scope.row)"
              style="margin-right: 5px; margin-bottom: 5px;"
            >
              <i class="el-icon-edit"></i> 编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteUserFollows(scope.row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { useUserInfoStore } from "../pinia/userinfo"

export default {
  data() {
    return {
      userFollowsList: [], 
      searchParams: {
        followerId: '', 
      },
      sprheaders: {
        uname: "",
        token: ""
      },
      addDialogVisible: false, 
      editDialogVisible: false, 
      addForm: {
        followerId: '',
        followedId: '',
        mutual: 0
      }, 
      editForm: {
        id: '',
        followerId: '',
        followedId: '',
        mutual: 0,
        createTime: '',
        updateTime: ''
      }, 
      loading: false,
      // 屏幕尺寸判断
      screenWidth: document.documentElement.clientWidth
    }
  },
  computed: {
    // 判断是否是桌面端
    isDesktop() {
      return this.screenWidth >= 1024;
    }
  },
  created() {
    const userStore = useUserInfoStore();
    this.sprheaders.uname = userStore.getUsername
    this.sprheaders.token = userStore.getToken
    this.loadUserFollowsList()
    
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // 处理窗口大小变化
    handleResize() {
      this.screenWidth = document.documentElement.clientWidth;
    },

    // 加载关注记录列表
    loadUserFollowsList() {
      this.loading = true;
      
      const params = {
        followerId: this.searchParams.followerId, 
      };

      axios.get(this.$baseUrl.SPRURL + "v2/userfollows/userfollows", {
        headers: this.sprheaders,
        params: params
      })
      .then(res => {
        if (res.data.code === 0) {
          this.userFollowsList = res.data.data || [];
          this.userFollowsList.forEach(item => {
            // 确保数值类型正确
            item.id = Number(item.id);
            item.followerId = Number(item.followerId);
            item.followedId = Number(item.followedId);
            item.mutual = Number(item.mutual);
          });
        } else {
          this.$message.error(res.data.msg || '数据加载失败');
        }
      })
      .catch(error => {
        console.error('API请求错误:', error);
        this.$message.error('网络请求失败，请重试');
      })
      .finally(() => {
        this.loading = false;
      });
    },

    // 显示添加对话框
    showAddDialog() {
      this.addDialogVisible = true;
      this.addForm = { 
        followerId: '',
        followedId: '',
        mutual: 0
      };
    },

    // 显示编辑对话框
    showEditDialog(row) {
      this.editDialogVisible = true;
      this.editForm = { 
        id: row.id,
        followerId: row.followerId,
        followedId: row.followedId,
        mutual: row.mutual,
        createTime: row.createTime,
        updateTime: row.updateTime
      };
    },

    // 添加关注记录
    addUserFollows() {
      // 验证表单
      this.$refs.addForm.validate((valid) => {
        if (!valid) {
          this.$message.warning('请填写所有必填字段');
          return;
        }

        // 转换为数值类型
        const payload = {
          ...this.addForm,
          followerId: Number(this.addForm.followerId),
          followedId: Number(this.addForm.followedId)
        };

        axios.post(this.$baseUrl.SPRURL + "v2/userfollows/userfollows", payload, {
          headers: this.sprheaders
        })
        .then(res => {
          if (res.data.code === 0) {
            this.$message.success('关注记录添加成功');
            this.addDialogVisible = false;
            this.loadUserFollowsList();
          } else {
            this.$message.error(res.data.msg || '关注记录添加失败');
          }
        })
        .catch(error => {
          console.error('添加关注记录错误:', error);
          this.$message.error('网络请求失败，请重试');
        });
      });
    },

    // 更新关注记录
    updateUserFollows() {
      // 验证表单
      this.$refs.editForm.validate((valid) => {
        if (!valid) {
          this.$message.warning('请填写所有必填字段');
          return;
        }

        // 转换为数值类型
        const payload = {
          ...this.editForm,
          followerId: Number(this.editForm.followerId),
          followedId: Number(this.editForm.followedId)
        };

        axios.put(this.$baseUrl.SPRURL + "v2/userfollows/userfollows", payload, {
          headers: this.sprheaders
        })
        .then(res => {
          if (res.data.code === 0) {
            this.$message.success('关注记录更新成功');
            this.editDialogVisible = false;
            this.loadUserFollowsList();
          } else {
            this.$message.error(res.data.msg || '关注记录更新失败');
          }
        })
        .catch(error => {
          console.error('更新关注记录错误:', error);
          this.$message.error('网络请求失败，请重试');
        });
      });
    },

    // 删除关注记录
    deleteUserFollows(row) {
      this.$confirm('确认删除该关注记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        axios.delete(this.$baseUrl.SPRURL + `v2/userfollows/userfollows/${row.id}`, {
          headers: this.sprheaders
        })
        .then(res => {
          if (res.data.code === 0) {
            this.$message.success('关注记录删除成功');
            this.loadUserFollowsList();
          } else {
            this.$message.error(res.data.msg || '关注记录删除失败');
          }
        })
        .catch(error => {
          console.error('删除关注记录错误:', error);
          this.$message.error('网络请求失败，请重试');
        });
      })
      .catch(() => {
        this.$message.info('已取消删除');
      });
    }
  }
}
</script>

<style scoped>
.user-follows-container {
  padding: 15px;
  background-color: #f8f9fa;
  min-height: 400px;
  position: relative;
}

.search-row {
  margin-bottom: 15px;
}

.button-group {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.el-table {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 状态容器样式 */
.state-container {
  min-height: 300px;
  position: relative;
}

/* 加载状态样式 */
.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

/* 空数据提示样式 */
.empty-data {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
  color: #909399;
}

.empty-data i {
  font-size: 40px;
  margin-bottom: 10px;
}

.empty-data p {
  margin-bottom: 20px;
  font-size: 16px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-table th, .el-table td {
    padding: 8px 0;
  }
  
  .el-button {
    padding: 8px 15px;
  }
}
</style>